using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class ErrorGUI : MonoBehaviour
{
    static List<string> ErrorMsgs = new List<string>();
    bool ShowWindow = false;
    bool Record = true;
    Rect UIRect = new Rect(0, Screen.height / 2, Screen.width, Screen.height / 2);
    Vector2 ScrollPosition = Vector2.zero;

    public StreamWriter sw;

    void Awake()
    {
        var fileName = Application.dataPath + "/log/log.txt";
        if (Application.platform == RuntimePlatform.Android)
        {
            fileName = Application.persistentDataPath + "/log/log.txt";
        }
        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
        }

        if (!File.Exists(fileName))
        {
            File.Create(fileName).Close();
        }
        File.WriteAllText(fileName, "");
        sw = new StreamWriter(fileName, true);
        Application.logMessageReceived += HandleLog;
    }
    void OnGUI()
    {
        if (ShowWindow)
        {
            if (GUI.Button(new Rect(0, (Screen.height / 3 + 90), 50, 30), "隐藏"))
            {
                ShowWindow = false;
            }
        }
        else
        {
            if (GUI.Button(new Rect(0, (Screen.height / 3 + 90), 50, 30), "显示"))
            {
                ShowWindow = true;
            }
        }
        if (ShowWindow)
        {
            UIRect = GUI.Window(1, UIRect, ErrorWindowFunc, "Log监听");
        }
    }
    void ErrorWindowFunc(int windowID)
    {
        GUI.DragWindow(new Rect(0, 0, UIRect.width, 30));
        GUI.Box(new Rect(0, 0, UIRect.width, UIRect.height), "");
        GUILayout.BeginArea(new Rect(5, 20, UIRect.width - 10, UIRect.height));
        ScrollPosition = GUILayout.BeginScrollView(ScrollPosition, GUILayout.Width(UIRect.width - 10), GUILayout.Height(UIRect.height - 60));
        GUILayout.BeginVertical();
        foreach (var Log in ErrorMsgs)
        {
            GUILayout.Label(Log);
        }
        GUILayout.EndVertical();
        GUILayout.EndScrollView();
        GUILayout.BeginHorizontal();
        if (Record)
        {
            if (GUILayout.Button("停止监听"))
            {
                Application.logMessageReceived -= HandleLog;
                Record = false;
            }
        }
        else
        {
            if (GUILayout.Button("监听Log"))
            {
                Application.logMessageReceived += HandleLog;
                Record = true;
            }
        }
        if (GUILayout.Button("清空记录"))
        {
            ErrorMsgs.Clear();
        }
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
    }

    void HandleLog(string log, string trace, LogType type)
    {
        ErrorMsgs.Add(log);
        ErrorMsgs.Add(trace);
    }
}

